<?php

include '../org_cookie.php';
// 简化版本 - 主要用于API密钥加载
$parsedResponse = [];
?>
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $current_org['cnorg'] ? $current_org['cnorg'].' - ' : ''; ?>Agent 内容编辑</title>
    <link href="https://cdn.staticfile.net/font-awesome/6.7.1/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.staticfile.net/tailwindcss/2.2.9/tailwind.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #6366f1;
            --secondary-color: #8b5cf6;
            --accent-color: #ec4899;
            --dark-bg: #0f172a;
            --dark-card: #1e293b;
            --light-bg: #f8fafc;
            --light-card: #ffffff;
        }

        body {
            font-family: 'Noto Sans SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            background: var(--light-bg);
            color: #1e293b;
            transition: all 0.3s ease;
        }

        body.dark-mode {
            background: var(--dark-bg);
            color: #e2e8f0;
        }

        .card {
            background: var(--light-card);
            transition: all 0.3s ease;
            border-radius: 1rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        .dark-mode .card {
            background: var(--dark-card);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.3), 0 2px 4px -1px rgba(0, 0, 0, 0.2);
        }
        /* 蓝色渐变按钮 (btn-primary) */
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            transition: all 0.3s ease;
            border: none;
            border-radius: 0.5rem;
            font-weight: 500;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(99, 102, 241, 0.3), 0 8px 10px -6px rgba(99, 102, 241, 0.2);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #64748b, #475569);
            color: white;
            border: none;
            border-radius: 0.5rem;
            font-weight: 500;
        }

        .btn-secondary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(100, 116, 139, 0.3), 0 8px 10px -6px rgba(100, 116, 139, 0.2);
        }

        /* 绿色渐变按钮 (btn-success) */
        .btn-success {
    --primary-color: #10b981; /* 翡翠绿 */
    --secondary-color: #34d399; /* 浅翡翠绿 */
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    color: white;
    transition: all 0.3s ease;
    border: none;
    border-radius: 0.5rem;
    font-weight: 500;
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px -5px rgba(16, 185, 129, 0.3), 0 8px 10px -6px rgba(16, 185, 129, 0.2);
}

/* 红色渐变按钮 (btn-danger) */
.btn-danger {
    --primary-color: #ef4444; /* 红色 */
    --secondary-color: #f87171; /* 浅红色 */
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    color: white;
    transition: all 0.3s ease;
    border: none;
    border-radius: 0.5rem;
    font-weight: 500;
}

.btn-danger:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px -5px rgba(239, 68, 68, 0.3), 0 8px 10px -6px rgba(239, 68, 68, 0.2);
}

/* 黄色渐变按钮 (btn-warning) */
.btn-warning {
    --primary-color: #f59e0b; /* 琥珀色 */
    --secondary-color: #fbbf24; /* 浅琥珀色 */
    background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
    color: white;
    transition: all 0.3s ease;
    border: none;
    border-radius: 0.5rem;
    font-weight: 500;
}

.btn-warning:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 25px -5px rgba(245, 158, 11, 0.3), 0 8px 10px -6px rgba(245, 158, 11, 0.2);
}


        .gradient-text {
            background: linear-gradient(135deg, var(--primary-color), var(--accent-color));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .tag-chip {
            background: rgba(99, 102, 241, 0.1);
            border: 1px solid rgba(99, 102, 241, 0.2);
            color: var(--primary-color);
            border-radius: 9999px;
            padding: 0.25rem 0.75rem;
            font-size: 0.875rem;
            font-weight: 500;
            transition: all 0.2s ease;
        }

        .dark-mode .tag-chip {
            background: rgba(147, 197, 253, 0.1);
            border: 1px solid rgba(147, 197, 253, 0.2);
            color: #93c5fd;
        }

        .result-section {
            border-left: 4px solid var(--primary-color);
            transition: all 0.3s ease;
        }

        .dark-mode .result-section {
            border-left: 4px solid #93c5fd;
        }

        .copy-btn {
            opacity: 0;
            transition: all 0.2s ease;
            background: rgba(100, 116, 139, 0.1);
            border: 1px solid rgba(100, 116, 139, 0.2);
            color: #64748b;
            border-radius: 0.5rem;
            padding: 0.5rem;
            cursor: pointer;
        }

        .result-item:hover .copy-btn {
            opacity: 1;
        }

        .glow-effect {
            box-shadow: 0 0 30px rgba(99, 102, 241, 0.15);
            transition: all 0.3s ease;
        }

        .dark-mode .glow-effect {
            box-shadow: 0 0 30px rgba(99, 102, 241, 0.25);
        }

        .animate-fade-in {
            animation: fadeIn 0.5s ease-in-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .progress-bar {
            height: 4px;
            background: linear-gradient(90deg, var(--primary-color), var(--secondary-color));
            animation: progressAnimation 2s infinite;
            border-radius: 9999px;
        }

        @keyframes progressAnimation {
            0% {
                transform: translateX(-100%);
            }

            100% {
                transform: translateX(100%);
            }
        }

        .file-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0.75rem;
            border-radius: 0.5rem;
            margin-bottom: 0.5rem;
            background: rgba(100, 116, 139, 0.05);
            transition: all 0.2s ease;
        }

        .dark-mode .file-item {
            background: rgba(100, 116, 139, 0.1);
        }

        .file-item:hover {
            background: rgba(99, 102, 241, 0.1);
            transform: translateX(5px);
        }

        .dark-mode .file-item:hover {
            background: rgba(147, 197, 253, 0.1);
        }

        .delete-btn {
            color: #ef4444;
            background: none;
            border: none;
            cursor: pointer;
            padding: 0.25rem;
            border-radius: 0.25rem;
            transition: all 0.2s ease;
        }

        .delete-btn:hover {
            background: rgba(239, 68, 68, 0.1);
            transform: scale(1.1);
        }

        .checkbox-group {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin: 1rem 0;
        }

        .checkbox-item {
            display: flex;
            align-items: center;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            background: rgba(100, 116, 139, 0.05);
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .dark-mode .checkbox-item {
            background: rgba(100, 116, 139, 0.1);
        }

        .checkbox-item:hover {
            background: rgba(99, 102, 241, 0.1);
        }

        .dark-mode .checkbox-item:hover {
            background: rgba(147, 197, 253, 0.1);
        }

        .checkbox-item input {
            margin-right: 0.5rem;
            accent-color: var(--primary-color);
        }

        .folder-input {
            position: relative;
        }

        .folder-input input {
            padding-right: 3rem;
        }

        .folder-input .folder-icon {
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #64748b;
        }

        /* 新增：上传区域样式 */
        #uploadForm {
            display: none;
        }

        .drag-active {
            border-color: #6366f1 !important;
            background-color: rgba(99, 102, 241, 0.05) !important;
        }
        
        /* 导航栏样式 */
        .navbar {
            background: rgba(255, 255, 255, 0.85) !important;
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .dark-mode .navbar {
            background: rgba(15, 23, 42, 0.85) !important;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        }

        .nav-link {
            color: #64748b;
            transition: all 0.2s ease;
            font-weight: 500;
        }

        .nav-link:hover {
            color: var(--primary-color);
        }

        .dark-mode .nav-link {
            color: #94a3b8;
        }

        .dark-mode .nav-link:hover {
            color: #c7d2fe;
        }

        .theme-toggle {
            background: transparent;
            border: 1px solid rgba(0, 0, 0, 0.1);
            color: #64748b;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }

        .dark-mode .theme-toggle {
            border: 1px solid rgba(255, 255, 255, 0.1);
            color: #94a3b8;
        }

        .theme-toggle:hover {
            background: rgba(99, 102, 241, 0.1);
            color: var(--primary-color);
            transform: rotate(15deg);
        }

        .dark-mode .theme-toggle:hover {
            background: rgba(99, 102, 241, 0.2);
        }
        
        /* API Key Input Styles */
        .api-key-input {
            position: relative;
        }

        .api-key-input input {
            padding-right: 80px;
        }

        .api-key-input .save-btn {
            position: absolute;
            right: 4px;
            top: 4px;
            bottom: 4px;
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            border: none;
            border-radius: 0.375rem;
            padding: 0 12px;
            font-size: 0.875rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .api-key-input .save-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 6px -1px rgba(99, 102, 241, 0.3), 0 2px 4px -1px rgba(99, 102, 241, 0.2);
        }
    </style>
</head>

<body class="min-h-screen transition-colors duration-300">
    <!-- 导航栏 -->
    <nav class="navbar sticky top-0 z-50">
        <div class="container mx-auto px-4">
            <div class="flex justify-between items-center h-16">
                <div class="flex items-center">
                    <div class="flex-shrink-0 flex items-center">
                        <div class="w-10 h-10 bg-gradient-to-r from-indigo-500 to-purple-600 rounded-xl flex items-center justify-center">
                            <i class="fas fa-robot text-white text-lg"></i>
                        </div>
                        <h1 class="text-xl font-bold text-gray-900 dark:text-white ml-3"><?php echo $current_org['cnorg'] ? $current_org['cnorg'].' - ' : ''; ?>GEO</h1>
                    </div>
                    <div class="hidden md:block ml-10">
                        <div class="flex items-baseline space-x-6">
                        <a href="index.php?login=<?php echo $login_org; ?>" target="_blank" class="nav-link">关键词分析</a>
                        <a href="content.php?login=<?php echo $login_org; ?>" target="_blank" class="nav-link">内容优化</a>
                            <a href="shuju.php?login=<?php echo $login_org; ?>" target="_blank" class="nav-link">数据整理</a>
                            <a href="https://app-77kgy52rwq9t.appmiaoda.com/" target="_blank" class="nav-link">搜索分析</a>
                            <a href="https://weixin.sogou.com/" target="_blank" class="nav-link">搜狗搜索</a>
                            <a href="https://texpeed.cn/" target="_blank" class="nav-link">文章排版</a>
                            <a href="https://modelscope.cn/models" target="_blank" class="nav-link">魔搭社区</a>
                            <a href="../main.php?login=<?php echo $login_org; ?>" class="nav-link">总控制台</a>
                        </div>
                    </div>
                </div>
                <div class="flex items-center">
                    <button id="themeToggle" class="theme-toggle">
                        <i class="fas fa-moon text-lg"></i>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <header class="mb-12 text-center">
            <h1 class="text-4xl md:text-5xl font-bold mb-4 gradient-text animate-fade-in">
                <i class="fas fa-brain mr-3"></i><?php echo $current_org['cnorg'] ? $current_org['cnorg'].' - ' : ''; ?> Agent 内容编辑
            </h1>
            <p class="text-xl text-gray-600 dark:text-gray-300 max-w-3xl mx-auto animate-fade-in" style="animation-delay: 0.2s;">
                基于Deepseek大模型 API，根据创意内容进行专业的内容创作。
            </p>

        </header>

        <!-- Main Content -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

            <!--  Input & Results -->
            <div class="lg:col-span-2">
                <!-- Single Processing -->
                <div class="card p-6 shadow-xl mb-8 glow-effect">
                    
                    

                    <!-- Text Content Source -->
                    <div class="mb-6">
                        <label for="textContentSource" class="block text-sm font-medium mb-2">文本内容引用源</label>
                        <textarea id="textContentSource" rows="20" placeholder="请输入多行文本内容，作为分析的主要文本来源..." class="w-full p-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all"></textarea>
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">输入的文本内容</p>
                    </div>

                    <!-- Process Button -->
                    <div class="w-full mb-6">
                        <button id="processBtn" class="btn-primary w-full py-3 rounded-lg font-medium flex items-center justify-center">
                            <i class="fas fa-magic mr-2"></i>开始智能创作
                        </button>
                    </div>

                    <!-- Progress Bar -->
                    <div id="progressContainer" class="hidden mb-6">
                        <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                            <div id="progressBar" class="progress-bar rounded-full h-2"></div>
                        </div>
                        <p id="progressText" class="text-sm text-center mt-2 text-gray-600 dark:text-gray-400">正在处理...</p>
                    </div>

                    <!-- Results -->
                    <div id="resultsContainer" class="hidden animate-fade-in">
                        
                        <!-- Results Tabs -->
                        <div class="mb-6 border-b border-gray-200 dark:border-gray-700">
                            <nav class="flex space-x-8">
                                <button class="result-tab active pb-4 font-medium text-indigo-600 dark:text-indigo-400 border-b-2 border-indigo-600 dark:border-indigo-400">
                                    <i class="fas fa-language mr-2"></i>创作内容
                                </button>
                                
                            </nav>
                        </div>

                        <!-- Tab Content -->
                        <div id="tabContent" class="space-y-6">
                            <!-- Chinese Description -->
                            <div class="result-section p-6 rounded-lg bg-gray-50 dark:bg-gray-800/50 border-l-4 border-indigo-500 dark:border-indigo-400 result-item">
                                <div class="flex justify-between items-center mb-3">
                                    <h3 class="font-semibold text-lg">★★内容描述★★</h3>
                                    <button class="copy-btn p-2 rounded-lg bg-gray-200 dark:bg-gray-700 hover:bg-indigo-100 dark:hover:bg-indigo-900/50 text-gray-600 dark:text-gray-300" data-clipboard-target="#chineseDesc">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                                <div id="chineseDesc" class="whitespace-pre-wrap text-gray-700 dark:text-gray-300 leading-relaxed"></div>
                            </div>

                            
                        </div>

                       
                        <!-- Response Info Display -->
                        <div id="responseInfo" class="mb-6 p-6 hidden">
                            <h3 class="font-semibold mb-3 flex items-center">
                                <i class="fas fa-info-circle mr-2 text-indigo-600 dark:text-indigo-400"></i>
                                响应信息
                            </h3>
                            <div class="bg-gray-100 dark:bg-gray-700 p-4 rounded-lg hidden">
                                <pre id="responseContent" class="text-sm text-gray-800 dark:text-gray-200 whitespace-pre-wrap"></pre>
                            </div>
                        </div>


                    </div>
                </div>

            </div>

            <!-- Settings Panel -->
            <div class="lg:col-span-1">
                <div class="card p-6 shadow-xl glow-effect">
                    <h2 class="text-2xl font-bold mb-6 flex items-center">
                        <i class="fas fa-cog mr-3 text-indigo-600 dark:text-indigo-400"></i>
                      Deepseek 内容创作
                    </h2>

                    <!-- DeepSeek API Info -->
                    <div class="mb-6">
                        <div class="bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
                            <div class="flex items-start">
                                <i class="fas fa-info-circle text-blue-600 dark:text-blue-400 mt-1 mr-3"></i>
                                <div>
                                    <h4 class="font-semibold text-blue-900 dark:text-blue-100 mb-2">Deepseek API 调用</h4>
                                    <div id="deepseekStatus" class="text-sm">
                                        <span class="text-gray-600 dark:text-gray-400">检查Deepseek API 状态...</span>
                                    </div>
                                    <div class="api-key-input mt-3">
                                        <input type="password" id="dpKeyInput" placeholder="请输入 DeepSeek API 密钥" class="w-full p-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all text-sm">
                                        <button id="saveDpKey" class="save-btn">保存</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- System Prompt -->
                    <div class="mb-6">
                        <div class="flex items-center justify-between mb-2">
                            <label for="systemPrompt" class="block text-sm font-medium">系统设定</label>
                            <select id="systemPromptSelect" class="text-sm p-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all">
                                <option value="">选择系统设定</option>
                            </select>
                        </div>
                        <textarea id="systemPrompt" rows="6" placeholder="系统提示词将自动填充..." class="w-full p-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all"></textarea>
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">选择系统设定自动填充提示词，或手动输入自定义提示词</p>
                    </div>

                    <!-- Custom Prompt -->
                    <div class="mb-6">
                        <div class="flex items-center justify-between mb-2">
                            <label for="customPrompt" class="block text-sm font-medium">用户提示词</label>
                            <select id="customPromptSelect" class="text-sm p-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all">
                                <option value="">选择用户提示词</option>
                            </select>
                        </div>
                        <textarea id="customPrompt" rows="4" placeholder="用户提示词将自动填充..." class="w-full p-3 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all"></textarea>
                        <p class="text-xs text-gray-500 dark:text-gray-400 mt-2">选择预设提示词自动填充，或手动输入自定义提示词指导AI分析</p>
                    </div>

                    <!-- Processing Options -->
                    <div class="mb-6">
                        <h3 class="font-semibold mb-3 flex items-center">
                            <i class="fas fa-sliders-h mr-2 text-indigo-600 dark:text-indigo-400"></i>
                            处理选项
                        </h3>
                        <div class="space-y-3">
                            <div class="flex items-center">
                                <input type="checkbox" id="autoCopy" class="mr-3 h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded">
                                <label for="autoCopy" class="text-sm">处理完成后自动复制结果</label>
                            </div>
                            <div class="flex items-center">
                                <input type="checkbox" id="showProgress" class="mr-3 h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded" checked>
                                <label for="showProgress" class="text-sm">显示处理进度</label>
                            </div>
                        </div>
                    </div>
                </div>

            </div>
            

        </div>

        <!-- Footer -->
        <footer class="mt-16 text-center text-gray-500 dark:text-gray-400">
            
            <p class="mt-2 text-sm">© 2025-2035 <?php echo $current_org['cnorg'] ? $current_org['cnorg'].' - ' : ''; ?>Agent 内容编辑. </p>
        </footer>
    </div>

    <script>
        // Theme Toggle
        const themeToggle = document.getElementById('themeToggle');
        const body = document.body;

        // Check for saved theme preference or use system preference
        const savedTheme = localStorage.getItem('theme');
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

        if (savedTheme === 'dark' || (!savedTheme && prefersDark)) {
            body.classList.add('dark-mode');
            themeToggle.innerHTML = '<i class="fas fa-sun text-lg"></i>';
        }

        themeToggle.addEventListener('click', () => {
            body.classList.toggle('dark-mode');
            if (body.classList.contains('dark-mode')) {
                themeToggle.innerHTML = '<i class="fas fa-sun text-lg"></i>';
                localStorage.setItem('theme', 'dark');
            } else {
                themeToggle.innerHTML = '<i class="fas fa-moon text-lg"></i>';
                localStorage.setItem('theme', 'light');
            }
        });

        // Initialize variables
        let deepseekStatus;

        // Check DeepSeek token availability
        async function checkDeepSeekToken() {
            if (!deepseekStatus) return;

            deepseekStatus.innerHTML = '<span class="text-yellow-600 dark:text-yellow-400"><i class="fas fa-spinner fa-spin mr-2"></i>检查API 调用中...</span>';

            try {
                // Check if DP_KEY exists in cookies
                const dpKey = getCookie('DP_KEY');
                if (dpKey) {
                    document.getElementById('dpKeyInput').value = dpKey;
                    deepseekStatus.innerHTML = '<span class="text-green-600 dark:text-green-400"><i class="fas fa-check-circle mr-2"></i>API 调用已配置，可以使用</span>';
                } else {
                    deepseekStatus.innerHTML = '<span class="text-red-600 dark:text-red-400"><i class="fas fa-exclamation-triangle mr-2"></i>API 调用未配置或不可用</span>';
                }
            } catch (error) {
                deepseekStatus.innerHTML = '<span class="text-red-600 dark:text-red-400"><i class="fas fa-exclamation-triangle mr-2"></i>无法检查API 调用状态</span>';
            }
        }

        
        // Initialize all DOM elements and event listeners
        function initializePage() {
            // Get DOM elements
            deepseekStatus = document.getElementById('deepseekStatus');
            const dpKeyInput = document.getElementById('dpKeyInput');
            const saveDpKey = document.getElementById('saveDpKey');
            const processBtn = document.getElementById('processBtn');
            const systemPromptSelect = document.getElementById('systemPromptSelect');
            const customPromptSelect = document.getElementById('customPromptSelect');

            console.log('DOM元素获取结果:', {
                deepseekStatus: !!deepseekStatus,
                dpKeyInput: !!dpKeyInput,
                saveDpKey: !!saveDpKey,
                processBtn: !!processBtn,
                systemPromptSelect: !!systemPromptSelect,
                customPromptSelect: !!customPromptSelect
            });

            if (!processBtn) {
                console.error('关键DOM元素未找到');
                return;
            }

            // Check DeepSeek token status
            checkDeepSeekToken();

            // Load system prompts and user prompts
            loadSystemPrompts();
            loadUserPrompts();

            // Save DP_KEY to cookie
            if (saveDpKey) {
                saveDpKey.addEventListener('click', () => {
                    const dpKey = dpKeyInput.value.trim();
                    if (dpKey) {
                        // Save to cookie with 30 days expiration
                        document.cookie = `DP_KEY=${dpKey}; max-age=${30 * 24 * 60 * 60}; path=/`;
                        showNotification('API 密钥已保存到本地 Cookie', 'success');
                        checkDeepSeekToken();
                    } else {
                        showNotification('请输入有效的 API 密钥', 'error');
                    }
                });
            }

            // Process button click handler
            processBtn.addEventListener('click', async () => {
                console.log('点击了开始内容创作按钮');

                const textContentSource = document.getElementById('textContentSource').value.trim();
                const customPrompt = document.getElementById('customPrompt').value.trim();
                const systemPrompt = document.getElementById('systemPrompt').value.trim();

                console.log('分析参数:', {
                    textContentSource: !!textContentSource
                });

                // Check if DP_KEY is available
                const dpKey = getCookie('DP_KEY');
                if (!dpKey) {
                    showNotification('请先配置 DeepSeek API 密钥', 'error');
                    return;
                }

                // 调用DeepSeek处理逻辑
                await processAnalysis( textContentSource, customPrompt, systemPrompt);
            });

            console.log('页面初始化完成');
        }

        // Load system prompts from agent/*.txt files
        async function loadSystemPrompts() {
            try {
                console.log('开始加载系统提示词...');
                const response = await fetch('./system_prompts_agent.php');
                const data = await response.json();

                console.log('系统提示词数据:', data);

                const systemPromptSelect = document.getElementById('systemPromptSelect');
                const systemPromptTextarea = document.getElementById('systemPrompt');

                if (!systemPromptSelect || !systemPromptTextarea) {
                    console.error('找不到系统提示词DOM元素');
                    return;
                }

                if (data.success && data.prompts) {
                    // Clear existing options except the first one
                    systemPromptSelect.innerHTML = '<option value="">选择系统设定</option>';

                    // Add system prompts to dropdown
                    data.prompts.forEach(prompt => {
                        const option = document.createElement('option');
                        option.value = prompt.content;
                        option.textContent = prompt.title;
                        systemPromptSelect.appendChild(option);
                        console.log('添加系统设定:', prompt.title);
                    });

                    // Set default to first prompt
                    if (data.prompts.length > 0) {
                        systemPromptTextarea.value = data.prompts[0].content;
                        systemPromptSelect.value = data.prompts[0].content;
                        console.log('设置默认系统设定:', data.prompts[0].title);
                    }
                } else {
                    console.error('加载系统提示词失败:', data.message || '未知错误');
                }
            } catch (error) {
                console.error('加载系统提示词失败:', error);
            }
        }

        // Load user prompts from jrd.json
        async function loadUserPrompts() {
            try {
                console.log('开始加载用户提示词...');
                const response = await fetch('./<?php echo isset($_COOKIE['enorg']) ? $_COOKIE['enorg'] : 'bozo'; ?>.json');
                const data = await response.json();

                console.log('用户提示词数据:', data);

                const customPromptSelect = document.getElementById('customPromptSelect');
                const customPromptTextarea = document.getElementById('customPrompt');

                if (!customPromptSelect || !customPromptTextarea) {
                    console.error('找不到用户提示词DOM元素');
                    return;
                }

                // Clear existing options except the first one
                customPromptSelect.innerHTML = '<option value="">选择用户提示词</option>';

                // Add user prompts to dropdown
                Object.entries(data).forEach(([title, content]) => {
                    const option = document.createElement('option');
                    option.value = content;
                    option.textContent = title;
                    customPromptSelect.appendChild(option);
                    console.log('添加用户提示词:', title);
                });

                // Set default to first prompt
                const firstKey = Object.keys(data)[0];
                if (firstKey) {
                    customPromptTextarea.value = data[firstKey];
                    customPromptSelect.value = data[firstKey];
                    console.log('设置默认用户提示词:', firstKey);
                }
            } catch (error) {
                console.error('加载用户提示词失败:', error);
            }
        }

        // Tab Navigation
        const resultTabs = document.querySelectorAll('.result-tab');
        const tabContents = document.querySelectorAll('#tabContent > div');

        resultTabs.forEach((tab, index) => {
            tab.addEventListener('click', () => {
                // Remove active class from all tabs
                resultTabs.forEach(t => t.classList.remove('active', 'text-indigo-600', 'dark:text-indigo-400', 'border-indigo-600', 'dark:border-indigo-400'));
                tab.classList.add('active', 'text-indigo-600', 'dark:text-indigo-400', 'border-indigo-600', 'dark:border-indigo-400');

                // Hide all tab contents
                tabContents.forEach(content => content.classList.add('hidden'));
                // Show selected tab content
                tabContents[index].classList.remove('hidden');
            });
        });

        // 从系统提示词选择器更新
        document.getElementById('systemPromptSelect').addEventListener('change', function() {
            document.getElementById('systemPrompt').value = this.value;
        });

        // 从用户提示词选择器更新
        document.getElementById('customPromptSelect').addEventListener('change', function() {
            document.getElementById('customPrompt').value = this.value;
        });

        // Process Analysis - 调用DeepSeek API进行分析
        async function processAnalysis(textContentSource, customPrompt, systemPrompt) {
            // Show progress
            const progressContainer = document.getElementById('progressContainer');
            const progressBar = document.getElementById('progressBar');
            const progressText = document.getElementById('progressText');
            const resultsContainer = document.getElementById('resultsContainer');
            
            progressContainer.classList.remove('hidden');
            resultsContainer.classList.add('hidden');

            try {
                // Simulate progress
                let progress = 0;
                const progressInterval = setInterval(() => {
                    progress += 5;
                    if (progress > 100) {
                        progress = 100;
                        clearInterval(progressInterval);
                    }
                    progressBar.style.width = progress + '%';
                    progressText.textContent = `正在处理... ${progress}%`;
                }, 200);

                // Call DeepSeek model API
                const result = await callDeepSeekAPI(textContentSource, customPrompt, systemPrompt);

                clearInterval(progressInterval);
                progressBar.style.width = '100%';
                progressText.textContent = '处理完成!';

                // Display results
                setTimeout(() => {
                    progressContainer.classList.add('hidden');
                    displayResults(result);
                    resultsContainer.classList.remove('hidden');

                    // Show response info
                    const responseInfo = document.getElementById('responseInfo');
                    const responseContent = document.getElementById('responseContent');
                    responseContent.textContent = result;
                    responseInfo.classList.remove('hidden');

                    // Auto copy if enabled
                    if (document.getElementById('autoCopy').checked) {
                        copyAllResults();
                        showNotification('结果已自动复制到剪贴板', 'success');
                    }
                }, 500);

            } catch (error) {
                progressContainer.classList.add('hidden');
                showNotification('处理失败: ' + error.message, 'error');
                console.error('Error:', error);

                // Display error response info
                const responseInfo = document.getElementById('responseInfo');
                const responseContent = document.getElementById('responseContent');
                responseContent.textContent = 'Error: ' + error.message;
                responseInfo.classList.remove('hidden');
            }
        }

        // Call DeepSeek API
        async function callDeepSeekAPI(textContentSource, customPrompt, systemPrompt) {
            // Combine system prompt, text content, and custom prompt
            const combinedText = `${systemPrompt}

${textContentSource}

${customPrompt}`;
            
            // Get DP_KEY from cookie
            const dpKey = getCookie('DP_KEY');
            
            const requestData = {
                model: "deepseek-chat",
                messages: [
                    {"role": "system", "content": combinedText},
                    {"role": "user", "content": textContentSource}
                ],
                stream: false
            };

            const response = await fetch('https://api.deepseek.com/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${dpKey}`
                },
                body: JSON.stringify(requestData)
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            if (!data.choices || data.choices.length === 0) {
                throw new Error('API调用失败');
            }

            return data.choices[0].message.content;
        }

        // Display Results - 直接显示文本内容
        function displayResults(result) {
            // 直接显示结果文本
            document.getElementById('chineseDesc').textContent = result;
            
            console.log('显示结果:', result);
        }

        // Copy functionality
        document.querySelectorAll('.copy-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const targetId = btn.getAttribute('data-clipboard-target');
                const targetElement = document.querySelector(targetId);

                if (targetElement) {
                    const textToCopy = targetElement.textContent;

                    navigator.clipboard.writeText(textToCopy).then(() => {
                        showNotification('已复制到剪贴板', 'success');
                    }).catch(err => {
                        console.error('复制失败:', err);
                        showNotification('复制失败', 'error');
                    });
                }
            });
        });

        // Copy all results
        function copyAllResults() {
            const chineseDesc = document.getElementById('chineseDesc').textContent;

            // 检查是否包含错误信息
            if (chineseDesc.includes('解析响应数据失败') || chineseDesc.includes('Error:')) {
                showNotification('当前显示的是错误信息，无法复制', 'error');
                return;
            }

            navigator.clipboard.writeText(chineseDesc).then(() => {
                showNotification('内容已复制到剪贴板', 'success');
            }).catch(err => {
                console.error('复制失败:', err);
                showNotification('复制失败', 'error');
            });
        }

        // Helper function to get cookie value
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
        }

        // Notification system
        function showNotification(message, type = 'info') {
            // Create notification element
            const notification = document.createElement('div');
            notification.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 transition-all duration-300 transform translate-x-full`;

            let bgColor, textColor, icon;
            switch (type) {
                case 'success':
                    bgColor = 'bg-green-500';
                    textColor = 'text-white';
                    icon = 'fas fa-check-circle';
                    break;
                case 'error':
                    bgColor = 'bg-red-500';
                    textColor = 'text-white';
                    icon = 'fas fa-exclamation-circle';
                    break;
                case 'info':
                    bgColor = 'bg-blue-500';
                    textColor = 'text-white';
                    icon = 'fas fa-info-circle';
                    break;
                default:
                    bgColor = 'bg-gray-500';
                    textColor = 'text-white';
                    icon = 'fas fa-bell';
            }

            notification.innerHTML = `
                <div class="flex items-center">
                    <i class="${icon} mr-3"></i>
                    <span>${message}</span>
                </div>
            `;
            notification.classList.add(bgColor, textColor);

            document.body.appendChild(notification);

            // Animate in
            setTimeout(() => {
                notification.classList.remove('translate-x-full');
                notification.classList.add('translate-x-0');
            }, 100);

            // Auto remove after 3 seconds
            setTimeout(() => {
                notification.classList.remove('translate-x-0');
                notification.classList.add('translate-x-full');
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 3000);
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializePage();
        });
    </script>
</body>

</html>